
// hook/tableList.js
/**
 * @description el-table的hook封装
 * 表格的属性设置，会覆盖默认的表格设置 可使用setProps
 * params.searchParams   除分页外的其他查询参数
 * params.afterListFun
 * params.delText      删除提示语
 * */

export default function useTableProps(params) {
	console.log('参数', params);
	const router = useRouter();
	const route = useRoute();
	const { proxy } = getCurrentInstance()
	// const goRefresh = inject('reload');

	// const message = inject("message")
	const {
		warningText = '',
		delText = '确认删除吗？',
		searchParams = {},
		detailForm = {},
		afterListFun = () => { },
		getDetailAfter = () => { }, // 获取详情的回调
		dealDetail = () => { }
	} = params
	const defaultProps = {
		pagination: {
			background: true,
			small: true,
			layout: 'total, sizes, prev, pager, next, jumper',
			pageSizes: [10, 20, 50, 100],
			total: 0,
			currentPage: 1,
			pageSize: 20
		},
		table: {
			border: true,
			rowKey: params.rowKey ? params.rowKey : 'id',
			data: []
		}

	};
	const detailId = ref('')
	const tableRef = ref()
	const date = ref()
	let loading = ref(false)
	// 属性组
	const propsRes = ref(defaultProps);
	const multipleSelection = ref([])
	// 加载效果
	const setLoading = (status) => {
		loading.value = status;
	};
	const searchTableList = async () => {
		propsRes.value.pagination.currentPage = 1
		params.getTableList ? params.getTableList() : getTableList()
	}
	/**
	 * 分页设置
	 * @param current //当前页数
	 * @param total //总页数默认是0条，可选
	 * @param fetchData 获取列表数据,可选
	 */

	const setPagination = ({ current, total }) => {
		propsRes.value.pagination.currentPage = current;
		total && (propsRes.value.pagination.total = total);
	};

	const showMessage = (val, type = 'success') => {
		proxy.$n(`${val}`, `${type}`)
	}

	// 单独设置默认属性
	const setProps = (val) => {
		for (const key in val) {
			defaultProps[key] = val[key];
		}
	};

	// 设置请求参数，如果出了分页参数还有搜索参数，在模板页面调用此方法，可以加入参数
	const loadListParams = ref(searchParams);
	const setLoadListParams = (params) => {
		loadListParams.value = params;
	};

	// 加载分页列表数据
	const getTableList = async () => {
		try {
			setLoading(true);
			let listParams = {
				...loadListParams.value,
				page: propsRes.value.pagination.currentPage,
				row: propsRes.value.pagination.pageSize
			}
			if (date.value?.length > 0) {
        listParams.startDate = date.value[0];
        listParams.endDate = date.value[1];
      } else {
        listParams.startDate = "";
        listParams.endDate = "";
      }
			console.log(listParams)
			let { data } = await params.url(listParams);
			console.log('列表', data.list)
			propsRes.value.table.data = data.list;
			setPagination({ current: data.page, total: data.rowsTotal });
			setLoading(false);
			afterListFun(listParams, data)
			if (!data.list.length) return data;
			console.log(detailId.value, '2222');

			//列表再次请求下 不重复设置setCurrentRow
			if (detailId.value) {
				let detail = data.list.find(item => item[propsRes.value.table.rowKey] == detailId.value)
				console.log(detail);
				if (detail) return data;
			}
			console.log(3333)
			//设置选中节点
			tableRef.value?.setCurrentRow(data.list[0])

			// if (!detailId.value) {
			// 	detailId.value = data.list[0].id;
			// }
			// tableRef.value?.setCurrentRow(data.list[0]);
			// let detail = data.list.find(
      //   (item) => item[propsRes.value.table.rowKey] == detailId.value
      // );
      // if (detail) return data;		
		} catch (e) {
			setLoading(false);
			console.log(e)
		}
	};

	const paginationEvent = ref({
		//分页触发
		currentChange: (current) => {
			propsRes.value.pagination.currentPage = current;
			params.getTableList ? params.getTableList() : getTableList();
		},
		// 修改每页显示条数
		sizeChange: (pageSize) => {
			propsRes.value.pagination.pageSize = pageSize;
			params.getTableList ? params.getTableList() : getTableList();
		}
	})

	// 表格事件触发组，可自行添加表格事件
	const tableEvent = ref({
		//排序触发
		sorterChange: (dataIndex, direction) => {
			console.log(dataIndex, direction);
		},
		selectionChange: (selection) => {
			console.log(11);
			multipleSelection.value = selection
		},
		currentChange: (val) => {
			if (val && detailId.value != val[propsRes.value.table.rowKey]) {
				detailId.value = val[propsRes.value.table.rowKey]
				params.detailUrl && getDetail()
			}
		}
	});

	// 列表删除
	const deletePage = async () => {
		try {
			if (!params.deleteAllUrl) return proxy.$n('请选择传入删除的方法！deleteUrl', 'warning')
			if (multipleSelection.value.length == 0) return proxy.$n('请选择数据！','warning')
			await proxy.$c(delText)
			let ids = multipleSelection.value.map(item => item[propsRes.value.table.rowKey])
			await params.deleteAllUrl({ ids })
			proxy.$n(`删除成功`);
			if (propsRes.value.pagination.currentPage > 1 && propsRes.value.table.data.length == multipleSelection.value.length) {
				propsRes.value.pagination.currentPage = propsRes.value.pagination.currentPage - 1
			}
			params.getTableList ? params.getTableList() : getTableList()
		} catch (e) {
			console.log(e)
		}
	}
	const getDetail = async () =>{
		try {
			console.log(detailForm);
			if (!detailId.value) return
			let inParams = {
				[propsRes.value.table.rowKey]: detailId.value
			}
			const {data: res} = await params.detailUrl(inParams)
			Object.keys(detailForm).forEach(item => {
				detailForm[item] = res[item]
			})
			detailForm.parentId = res.parentId || "";
			console.log(detailForm);
			dealDetail(detailForm)
			getDetailAfter(res)
		} catch (err) {
			console.log(err);
		}
  }
	// 删除数据
	const deleteItem = async (id) => {
		try {
			if (!(detailId.value ? detailId.value : id)) {
				proxy.$n('请选择待删除选项！', 'warning');
				return
			}
			// await proxy.$c()
			await params.deleteUrl({id: detailId.value ? detailId.value :id})
			console.log(555);
			proxy.$n()
			if (propsRes.value.table.data.length == 1 && propsRes.value.pagination.currentPage > 0) {
				propsRes.value.pagination.currentPage--
			}
			params.getTableList ? params.getTableList() : getTableList()
		} catch (err) {
			console.log(err);
		}
	}
	// 刷新
	const refreshPage = () => {
		console.log(route);
		goRefresh();
	}
	// 刷新
	const resetTable = () => {
		propsRes.value.pagination.currentPage = 1
		propsRes.value.pagination.pageSize = 20
		propsRes.value.pagination.total = 0
		propsRes.value.table.data = []
		
	}
  // 返回
  const roteBack = () => {
    router.back()
  }
	return {
		date,
		tableRef,
		detailId,
		propsRes,
		loading,
		tableEvent,
		paginationEvent,
		multipleSelection,
		router,
		route,
		proxy,
		resetTable,
		getDetail,
		deleteItem,
		setProps,
		setLoading,
		searchTableList,
		getTableList,
		setPagination,
		roteBack,
		setLoadListParams,
		deletePage,
		refreshPage,
		showMessage,
	};
}
